const axios = require("axios");
const cheerio = require("cheerio");
const Koa = require("koa");
const app = new Koa();
const fs = require("fs");
let titles = "";
const path = require("path");
async function scrapeWebsite() {
  try {
    const data = fs.readFileSync(path.join(__dirname, "index.html"));
    const $ = cheerio.load(data);

    // titles = $('meta[name="keywords"]').attr("content");

    // 标签选择器
    // titles += $(".container").html();
    // titles += $("ul").find("li").text();
    $("ul li").after("<li>6</li>");
    titles += `<div>${$("ul").html()}</div>`;

    // each方法
    // $("ul li").each((index, ele) => {
    //   titles += $(ele).html();
    // });

    // console.log(data);
  } catch (error) {
    console.error("爬取失败：", error.message);
  }
}

app.use(async (ctx, next) => {
  await scrapeWebsite();
  ctx.body = `
  <!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="keywords" content="zzzksNode+爬虫教程" />
    <title>Document</title>
  </head>
  <body>
   ${titles}
    
  </body>
</html>
`;
  await next();
});

// 监听端口
app.listen(3000, () => {
  console.log("Server is running on http://localhost:3000");
});
